package com.brkj.main;

import com.dgl.sdk.util.Utils;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.annotation.view.ViewInject;

import com.brkj.course.WebViewTestActivity;
import com.brkj.httpInterface.BaseAjaxParams;
import android.content.Intent;
import android.os.Bundle;
import android.provider.SyncStateContract.Constants;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.brkj.model.DS_MyInfo;
import com.brkj.main.R;
import com.brkj.httpInterface.HttpInterface;
import com.brkj.httpInterface.HttpInterface.HIF_ConfirmUserInfo;
import com.brkj.httpInterface.HttpInterface.HIF_Login;
import com.brkj.httpInterface.HttpInterface.HIF_SubmitUserInfoError;
import com.brkj.util.ActivityStackControlUtil;
import com.brkj.util.ConstAnts;
import com.brkj.util.JsonUtil;
import com.brkj.util.MyAjaxCallBack;
import com.brkj.util.MyApplication;
import com.brkj.util.SharePrefSaver;
import com.brkj.util.view.BaseActivity;
import com.brkj.util.view.WidgetAnim;
import com.dgl.sdk.util.SharePreStore;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;

public class LoginActivity extends BaseActivity{

	 @ViewInject(id=R.id.userName) View parentView;
	 @ViewInject(id=R.id.userName) EditText userName;
	 @ViewInject(id=R.id.password) EditText passWord;
	 @ViewInject(id=R.id.findPassWord,click="findPassWord") TextView findPassWord;
	 @ViewInject(id=R.id.login,click="loginClick") Button login;
	 @ViewInject(id=R.id.regeist,click="regeistClick") Button regeist;
	 @ViewInject(id=R.id.autoLogin,click="autoLoginClick") CheckBox autoLogin;
	
	 @ViewInject(id=R.id.adress) EditText adress;
	 @ViewInject(id=R.id.fixAdress,click="click_fixAdress") Button fixAdress;
	 @ViewInject(id=R.id.webTest,click="click_webTest") Button webTest;
	 
	 

	private PopupWindow popupWindow;
	private long exitTime;
	 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		setAnimType(BaseActivity.RIGHT_ENTER_LEFT_EXT);
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.login);

		final SharePrefSaver  saver = new SharePrefSaver(LoginActivity.this, "autoLogin");
		saver.save("ifAutoLogin", autoLogin.isChecked());
		autoLogin.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			
				saver.save("ifAutoLogin", isChecked);
				
			}
		});
		
		//调试代码
		if(MyApplication.isDebug){
			userName.setText("admin");
			passWord.setText("bori654321");
			
			adress.setVisibility(View.VISIBLE);
			fixAdress.setVisibility(View.VISIBLE);
			
			adress.setText(SharePreStore.readString(ConstAnts.SP_KEY_FIXADRESS));
			
		}else{
			adress.setVisibility(View.GONE);
			fixAdress.setVisibility(View.GONE);
			webTest.setVisibility(View.GONE);
		}
	}


	public void loginClick(View v){

//        if(MyApplication.isDebug){
//            gotoMainTabActivity();
//        }

		String name = userName.getText().toString();
		String pw = passWord.getText().toString();
		if(name.equals("")){
			WidgetAnim.StartLRAnim(this, userName);
			return;
		}
		if(pw.equals("")){
			WidgetAnim.StartLRAnim(this, passWord);
			return;
		}
		
		
		BaseAjaxParams params = new BaseAjaxParams();
		  params.put(HIF_Login.params.UserName, name);
		  params.put(HIF_Login.params.PWD, pw);

		  FinalHttp fh = new FinalHttp();
		  fh.post(HIF_Login.address, params, new MyAjaxCallBack<Object>(this){

			@Override
			public void onSuccess(Object t) {
				super.onSuccess(t);
				
				HIF_Login.result result = 
						JsonUtil.fromJson((String)t, HIF_Login.result.class);
				
				if(result == null){
					showToast("未知错误！");
					return;
				}
				
				if(result.result == 0){
					
					showToast(result.reason);
					
				}else if(result.result == 1){
					try {
						//保存我的信息
						DS_MyInfo myInfo = result.userInfo;
						myInfo.saveInfo();
						MyApplication.updateMyinfo();
						
						if(result.ifFirstLogin == 1){
//							showUserInfo_PopupWindow();
							gotoMainTabActivity();
							
						}else{
							
							showUserInfo_PopupWindow();
						}
					} catch (Exception e) {
						showToast("登录失败！");
					}

					
				}
				progressDialog.dismiss();
			}
			  
		  });
	}
	
	public void regeistClick(View v){
		Intent intent = new Intent(this, RegistAcivity.class);
		startActivity(intent);
	}
	
	public void autoLoginClick(View v){
		
	}
	
	public void findPassWord(View v){
		Intent intent = new Intent(this, FindPassWordAcivity.class);
		startActivity(intent);
	}
	
	
	private void showUserInfo_PopupWindow() {
		View popupWindow_view = getLayoutInflater().inflate(
				R.layout.user_info_confirm, null, false);
		popupWindow = new PopupWindow(popupWindow_view,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);// 创建PopupWindow实例

		popupWindow.setFocusable(true);
//		popupWindow.setOutsideTouchable(true);
		// popupWindow.setAnimationStyle(R.style.PopWindowAnim);
//		popupWindow.setBackgroundDrawable(new ColorDrawable(0));
//		popupWindow.setBackgroundDrawable(new ColorDrawable(0x7DC0C0C0));
//		popupWindow.update();
		
		((TextView)popupWindow_view.findViewById(R.id.userAcount)).setText(MyApplication.myInfo.getUserAcount());
		((TextView)popupWindow_view.findViewById(R.id.name)).setText(MyApplication.myInfo.getName());
		((TextView)popupWindow_view.findViewById(R.id.gender)).setText(MyApplication.myInfo.getGender());
		((TextView)popupWindow_view.findViewById(R.id.department)).setText(MyApplication.myInfo.getDepartment());
		((TextView)popupWindow_view.findViewById(R.id.post)).setText(MyApplication.myInfo.getPost());

		popupWindow_view.findViewById(R.id.confirm).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				confirmUserInfo();
				popupWindow.dismiss();
				
			}
		});
		popupWindow_view.findViewById(R.id.cancle).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				submitUserInfoError();
				popupWindow.dismiss();
				
			}
		});

		popupWindow.showAtLocation(parentView, Gravity.CENTER, 0, 0);
	}
	
	private void confirmUserInfo(){
		FinalHttp fh = new FinalHttp();
		BaseAjaxParams params = new BaseAjaxParams();
		params.put(HIF_ConfirmUserInfo.params.UserName, MyApplication.myInfo.getUserAcount());
		
		fh.post(HIF_ConfirmUserInfo.address, params, new MyAjaxCallBack<Object>(this){

			@Override
			public void onSuccess(Object t) {
				super.onSuccess(t);
				
				Gson gson = new Gson();
				HIF_ConfirmUserInfo.result result = 
						gson.fromJson((String)t, HIF_ConfirmUserInfo.result.class);
				
				if(result.result == 0){
					
					showToast(result.reason);
					
				}else if(result.result == 1){
					
					gotoMainTabActivity();
					
				}
			}
			
		});
	}
	
	protected void submitUserInfoError() {
		FinalHttp fh = new FinalHttp();
		BaseAjaxParams params = new BaseAjaxParams();
		params.put(HIF_SubmitUserInfoError.params.UserName, MyApplication.myInfo.getUserAcount());
		params.put(HIF_SubmitUserInfoError.params.PhoneNum, "13888888888"); //undo
		
		fh.post(HIF_SubmitUserInfoError.address, params, new MyAjaxCallBack<Object>(this){

			@Override
			public void onSuccess(Object t) {
				super.onSuccess(t);
				
				Gson gson = new Gson();
				HIF_SubmitUserInfoError.result result = 
						gson.fromJson((String)t, HIF_SubmitUserInfoError.result.class);
				
				if(result.result == 0){
					showToast(result.reason);
					
				}else if(result.result == 1){
					
					showToast("已记录，等待管理员与你联系更正！");
					
				}
			}
			
		});
	}


	private void gotoMainTabActivity(){
		Intent intent = new Intent(this, MainTabActivity.class);
		startActivity(intent);
	}
	
	public void click_fixAdress(View v){
		if(WidgetAnim.checkIfEmpty(this, adress)){
			return;
		}
		String fixAdress = adress.getText().toString();
		HttpInterface.WEB_ADDRESS = "http://" + fixAdress + "/KMELearning/andorid/";
		
		SharePreStore.save(ConstAnts.SP_KEY_FIXADRESS, fixAdress);
	}
	
	public void click_webTest(View v){
		
		showActivity(WebViewTestActivity.class);
//        File file = new File(ConstAnts.DOWNLOAD_COURSE__DIR, "1804570330");
//        try {
//            Utils.upZipFile(file, ConstAnts.DOWNLOAD_COURSE__DIR);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK ) {
	        if((System.currentTimeMillis() - exitTime) > 2000){
	            showToast("再按一次退出掌上学苑 ");
	            exitTime = System.currentTimeMillis();
	        } else {
	        	ActivityStackControlUtil.finishProgram();
	        }
		}
		
		return true;
	}
}
